/**
 * projectName: palmdoctor-mb-backend
 * fileName: RequestUtil.java
 * packageName: com.palmdoctor.mb.utils
 * date: 2021-05-07 13:43
 * copyright(c) 2021 http://www.hydee.cn/ Inc. All rights reserved.
 */
package com.zny.sescore.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zny.sescore.exception.BizException;
import com.zny.sescore.exception.MessageEnum;
import com.zny.sescore.model.LoginInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @version: V1.0
 * @author: zhangnayi
 * @className: RequestUtil
 * @packageName: com.palmdoctor.mb.utils
 * @description:
 * @data: 2021-05-07 13:43
 **/
@Slf4j
@Component
public class RequestUtil {

    private static Integer defaultHospitalId;

    public static LoginInfo getLoginUser() {
        if (isLoginIn()) {
            try {
                return (LoginInfo) SecurityUtils.getSubject().getPrincipal();
            } catch (Exception e) {
                throw new BizException(MessageEnum.UNAUTHORIZED);
            }
        }
        throw new BizException(MessageEnum.UNAUTHORIZED);
    }

    public static String getLoginUserName() {
        if (isLoginIn()) {
            return getLoginUser().getUserName();
        } else if (EnvironmentUtil.isDevMode()) {
            return "测试";
        }
        return null;
    }

    public static String getMobile() {
        return getLoginUser().getMobile();
    }

    public static Integer getLoginUserId() {
        if (isLoginIn()) {
            return getLoginUser().getUserId();
        } else if (EnvironmentUtil.isDevMode()) {
            return 3;
        }
        return null;
    }

    public static Integer getSystemId() {
        return getLoginUser().getSystemId();
    }

    public static boolean isLoginIn() {
        try {
            return SecurityUtils.getSubject() != null
                    && SecurityUtils.getSubject().getPrincipal() != null;
        } catch (Exception e) {
            return false;
        }
    }

    public static List<LoginInfo.Permission> getPermissions() {
        return getLoginUser().getPermissions();
    }

    public static String getIpAddress() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    public static int getPort() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getServerPort();
    }

    public static String getHost() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = request.getRequestURL().toString();
        if (StringUtils.isBlank(url)) {
            return url;
        }
        //url经过转发后,https会变成http,用header X-Forwarded-Proto 来标记最迟的请求方式
        //X-Forwarded-Proto需要在nginx中配置好proxy_set_header X-Forwarded-Proto $scheme;
        String proto = request.getHeader("X-Forwarded-Proto");
        if ("https".equalsIgnoreCase(proto) && !url.contains("https://")) {
            url = url.replaceAll("http://", "https://");
        }
        return url.substring(0, url.indexOf("/", 8));
    }

    @Value("${global-setting.hospital-id}")
    private void setDefaultHospitalId(Integer hospitalId) {
        RequestUtil.defaultHospitalId = hospitalId;
    }

}